import jwt
from fastapi import Depends, Header, HTTPException, Request
from sqlalchemy.orm import Session
from .models import Log

from core.database import SessionLocal


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


def common_dependencies(db: Session = Depends(get_db), token: str = Header(None)):
    if token is None:
        raise HTTPException(status_code=401, detail="Token missing")
    try:
        payload = jwt.decode(token, "demo-key", algorithms='HS256')
        return {"db": db, "user_id": payload.get("user_id"), "username": payload.get("username")}
    except jwt.ExpiredSignatureError:
        raise HTTPException(status_code=401, detail="Token invalid")


def common_dependencies_no_auth(db: Session = Depends(get_db)):
    return {"db": db, "user_id": None, "username": None}


def log_route(request: Request, common: dict = Depends(common_dependencies)):
    username = common["username"]
    if username is None:
        username = "unknown"
    log = Log(uri=str(request.url), operator=username)
    common["db"].add(log)
    common["db"].commit()


def log_route_no_auth(request: Request, common: dict = Depends(common_dependencies_no_auth)):
    log = Log(uri=str(request.url), operator=common.get("username", "unknown"))
    common["db"].add(log)
    common["db"].commit()
